<?php

namespace App\Http\Controllers;

use App\Http\Requests;
use App\Services\Common;
use App\Services\Store;
use DB;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Ixudra\Curl\Facades\Curl;

class MobileShopController extends Controller
{
    // 商店卖出商品
    public function shopSellGoods(Request $request){

        $auCode = $request->auCode;
        $sCode = $request->sCode;
        $sgId = $request->sgId;
        $sellNum = $request->sellNum;
        $memo = $request->memo;

        if (!$auCode || !$sCode || !$sgId || !$sellNum){
            return $this->returnMsg(0, '缺少必要参数('.$auCode.'|'.$sCode.'|'.$sgId.')');
        }

        $sInfo = DB::table('store')->where('sCode', $sCode)->first();
        if (empty($sInfo)){
            return $this->returnMsg(0, '找不到店铺对象');
        }

        $sgIdArray = \explode('|', $sgId);

        $priceStr = '';
        for($i=0;$i<count($sgIdArray);$i++){
            $settlePrice = DB::select("SELECT agp.goodsPrice
FROM agency_goods_price AS agp
LEFT JOIN agency_level AS al ON agp.alLevel = al.alLevel
LEFT JOIN admin_users AS au ON au.alId = al.alId
WHERE au.auCode = ? AND agp.goodsId = ? ", [$auCode, $sgIdArray[$i]]);
            if (empty($settlePrice)){
                return $this->returnMsg(0, '找不到该商品对应价格');
            }
            $priceStr = $priceStr.'|'. $settlePrice[0]->goodsPrice;
        }
        $priceStr = \substr($priceStr, 1);

        $Common = new Common();
        $result = $Common->sellGoods($sInfo->sId, $auCode, $sgId, $sellNum, $priceStr, $memo,
								'mobileShop', '', '代理', 0, 0, false, $auCode, false);

        if ($result !== true){
        	return $this->returnMsg(0, $result);
        }

        $orderId = Cache::pull($auCode.'_selling');

        return $this->returnMsg(1, 'OK', ['orderId'=>$orderId]);
    }

    // 获取商品库存
    public function getGoodsNum(Request $request){

        $auCode = $request->auCode;
        $sCode = $request->sCode;
        $sgId = $request->sgId;

        $sgNum =  DB::table('store_goods')->where('sgId', $sgId)->value('sgNum');

        return $this->returnMsg(1, 'OK', $sgNum);
    }

    // 取消出库
    public function channelOrder(Request $request){

        $sgoOrderId = $request->sgoOrderId;
        $createUser = $request->createUser;

        $sgoInfo = DB::table('store_goods_out')->where('sgoOrderId', $sgoOrderId)->first();
        if (empty($sgoInfo)){
            return $this->returnMsg(0, '系统错误，找不到该出库单');
        }

        $Store = new Store();
        $result = $Store->channelGoodsOut($sgoInfo->sgoId, $createUser);
        if ($result === true){
            return $this->returnMsg(1, 'OK');
        }else{
            return $this->returnMsg(0, $result);
        }
    }
}
